"""
    upload_file_directly.py

    MediaWiki API Demos
    Demo of `Upload` module: Sending post request to upload a file directly

    MIT license
"""

import os
import sys
import pathlib
import requests

# 只需要改这3个变量用于登录
LGNAME = "admin"
LGPASSWORD = "adminOrg2022"
URL = "http://www.orangepi.cn/orangepiwiki/api.php"

# 要上传的文件所处的文件夹
# FILE_DIR = "media"

S = requests.Session()

# Step 1: Retrieve a login token
PARAMS_1 = {"action": "query", "meta": "tokens", "type": "login", "format": "json"}

R = S.get(url=URL, params=PARAMS_1)
DATA = R.json()

LOGIN_TOKEN = DATA["query"]["tokens"]["logintoken"]

# Step 2: Send a post request to login. Use of main account for login is not
# supported. Obtain credentials via Special:BotPasswords
# (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
PARAMS_2 = {
    "action": "login",
    "lgname": LGNAME,
    "lgpassword": LGPASSWORD,
    "format": "json",
    "lgtoken": LOGIN_TOKEN,
}

R = S.post(URL, data=PARAMS_2)

# Step 3: Obtain a CSRF token
PARAMS_3 = {"action": "query", "meta": "tokens", "format": "json"}

R = S.get(url=URL, params=PARAMS_3)
DATA = R.json()

CSRF_TOKEN = DATA["query"]["tokens"]["csrftoken"]


def upload_file(filename, file_path):
    # Step 4: Post request to upload a file directly
    PARAMS_4 = {
        "action": "upload",
        "filename": filename,
        "format": "json",
        "token": CSRF_TOKEN,
        "ignorewarnings": 1,
    }

    FILE = {"file": (filename, open(file_path, "rb"), "multipart/form-data")}

    R = S.post(URL, files=FILE, data=PARAMS_4)
    DATA = R.json().get("upload", {}).get("result")
    print(DATA)


# # 提问输入前缀
# prefix = input("请输入前缀: ")

# if not prefix:
#     sys.exit("请输入前缀")

if __name__ == "__main__":
    # 获取传参 argvs
    media_path = sys.argv[1].strip('"')
    media_path = pathlib.Path(media_path).as_posix()

    if not media_path:
        print("请传入文件路径")
        sys.exit(1)

    if not os.path.isdir(media_path):
        print("目录不存在")
        sys.exit(1)

    # 列出media文件夹下所有的文件, 调用upload_file函数上传
    media_files = os.listdir(media_path)
    for i, filename in enumerate(media_files):
        filepath = os.path.join(media_path, filename)
        # filename = prefix + filename
        print(f"{i+1}/{len(media_files)} {filename}: {filepath}")
        upload_file(filename, filepath)
